var express = require('express')
var router = express.Router()
var DB = require('../../modules/db.js')
var multiparty = require('multiparty')
var fs = require('fs')

router.get('/', function(req, res) {
  DB.find('product', {}, function(err, data) {
    res.render('product', {
      list: data
    })
  })
})
router.get('/add', function(req, res) {
  res.render('productadd')
})
router.post('/doAdd', function(req, res) {
  var form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, function(err, fields, files) {
    var title = fields.title[0]
    var price = fields.price[0]
    var fee = fields.fee[0]
    var description = fields.description[0]
    var pic = files.pic[0].path
    DB.insert('product', { title, price, fee, description, pic }, function(
      err,
      data
    ) {
      if (!err) {
        res.redirect('product')
      }
    })
  })
})
router.get('/edit', function(req, res) {
  var id = req.query.id
  DB.find('product', { _id: new DB.ObjectID(id) }, function(err, data) {
    res.render('productedit', {
      list: data[0]
    })
  })
})

router.post('/doEdit', function(req, res) {
  var form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, function(err, fields, files) {
    var _id = fields._id[0]
    var title = fields.title[0]
    var price = fields.price[0]
    var fee = fields.fee[0]
    var description = fields.description[0]
    var originalFilename = files.pic[0].originalFilename
    var pic = files.pic[0].path
    if (originalFilename) {
      var setData = {
        title,
        price,
        fee,
        description,
        pic
      }
    } else {
      var setData = {
        title,
        price,
        fee,
        description
      }
      fs.unlink(pic)
    }
    DB.update('product', { _id: new DB.ObjectID(_id) }, setData, function(
      err,
      data
    ) {
      if (!err) {
        res.redirect('/product')
      }
    })
  })
})
router.get('/delete', function(req, res) {
  var id = req.query.id
  DB.deleteOne('product', { _id: new DB.ObjectID(id) }, function(err, data) {
    if (!err) {
      res.redirect('/product')
    }
  })
})

module.exports = router
